package com.drug.mingkang.service.impl;

import cn.hutool.core.date.DateUtil;
import com.drug.mingkang.mapper.AuditRecordMapper;
import com.drug.mingkang.mapper.HqFinancingMapper;
import com.drug.mingkang.mapper.HqPurchaseorderMapper;
import com.drug.mingkang.mapper.HqRicherMapper;
import com.drug.mingkang.model.*;
import com.drug.mingkang.model.vo.PurchaseAddVo;
import com.drug.mingkang.model.vo.PurchaseMaterialVo;
import com.drug.mingkang.model.vo.PurchaseorderVo;
import com.drug.mingkang.model.vo.rawMaterialVo;
import com.drug.mingkang.permission.model.PerUsers;
import com.drug.mingkang.service.*;
import com.drug.mingkang.utils.AuditStatus;
import com.drug.mingkang.utils.ResponseMessage;
import com.drug.mingkang.utils.Tools;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 原材料采购单(HqPurchaseorder)表服务实现类
 *
 * @author wenchangjian
 * @since 2020-08-11 12:00:13
 */
@Service("hqPurchaseorderService")
public class HqPurchaseorderServiceImpl implements HqPurchaseorderService {

    @Resource
    private HqPurchaseorderMapper hqPurchaseorderMapper;
    @Resource
    private AuditRecordService auditRecordService;
    @Resource
    private HqPurchasedetailsService hqPurchasedetailsService;
    @Resource
    private HqInventoryService hqInventoryService;
    @Resource
    private AuditRecordMapper auditRecordMapper;
    @Resource
    private HqWarehousingService hqWarehousingService;

    /**
     * 总公司财务服务
     */
    @Resource
    private HqFinancingMapper hqFinancingMapper;

    /**
     * 总公司财务明细服务
     */
    @Resource
    private HqRicherMapper hqRicherMapper;

    @Override
    public List<HqPurchaseorder> queryReviewByLimit(PurchaseorderVo purchaseorderVo) {
        return this.hqPurchaseorderMapper.queryReviewByLimit(purchaseorderVo);
    }

    @Override
    public boolean insertJoinTheInventory(String purchaseId, HttpSession session) {
        //根据订单查询所有原材料
        List<Map<String,Object>> map=hqPurchasedetailsService.queryAllmaterial(purchaseId);
        //初始化总公司库存
        HqInventory update = null;
        //获取当前登录用户
        PerUsers perUsers = (PerUsers)session.getAttribute("perUsers");
        //map 判断
        if (!map.isEmpty()) {
            for (Map<String, Object> maps : map) {
                //获取数量以及原材料id
                Integer count = (Integer) maps.get("count");
                String materialId = (String) maps.get("materialId");
                //查询单个原材料
                HqInventory hqInventory=hqInventoryService.selectMaterialId(materialId);
                //查询库存 存在就修改否则增加
                //设置操作人 原材料 以及数量
                if (hqInventory!=null){
                    hqInventory.setOper(perUsers.getUserName());
                    if (hqInventory.getInventoryNum()==null){
                        hqInventory.setInventoryNum(0);
                    }
                    System.err.println("======"+hqInventory.getInventoryNum()+"==="+count);
                    hqInventory.setInventoryNum(hqInventory.getInventoryNum()+count);
                    update = hqInventoryService.update(hqInventory);
                }else {
                    HqInventory hqInventory1=new HqInventory();
                    hqInventory1.setOper(perUsers.getUserName());
                    hqInventory1.setMaterialId(materialId);
                    hqInventory1.setInventoryNum(count);
                    update = hqInventoryService.insert(hqInventory1);
                }
                //库存明细增加
                HqWarehousing hqWarehousing=new HqWarehousing();
                hqWarehousing.setInventoryId(update.getInventoryId());
                hqWarehousing.setWareNum(count);
                hqWarehousing.setOper(perUsers.getUserName());
                hqWarehousing.setState(1);
                hqWarehousingService.insert(hqWarehousing);
            }
            hqPurchaseorderMapper.updateisva(purchaseId,AuditStatus.NO_YRK.status);
        }
        return update != null;
    }

    @Override
    public int selectReviewCount(PurchaseorderVo purchaseorderVo) {
        return this.hqPurchaseorderMapper.selectReviewCount(purchaseorderVo);
    }

    @Override
    public int insert(String arr, String remark, String supId,HttpSession session) {
        List<PurchaseAddVo> list = new Tools().jsonToList(arr, PurchaseAddVo.class);
        double Money = 0;
        HqPurchaseorder hqPurchaseorder = new HqPurchaseorder();
        //供应商Id
        hqPurchaseorder.setSupId(supId);
        //获取当前登录用户
        PerUsers perUsers = (PerUsers)session.getAttribute("perUsers");
        hqPurchaseorder.setOper(perUsers.getUserName());
        hqPurchaseorder.setPurchasePerson(perUsers.getUserName());
        //备注
        hqPurchaseorder.setRemark(remark);
        //未申请
        hqPurchaseorder.setIsva(AuditStatus.NO_SQ.status);
        //采购时间
        String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        hqPurchaseorder.setPurchaseTime(DateUtil.parse(dateStr));
        for (PurchaseAddVo purchaseAddVo : list) {
            //总价格
            Money += purchaseAddVo.getMoney() * purchaseAddVo.getCount();
        }
        //总金额
        hqPurchaseorder.setPurchaseSumprice(Money);
        int insert = hqPurchaseorderMapper.insert(hqPurchaseorder);
        for (PurchaseAddVo purchaseAddVo : list) {
            //采购明细
            HqPurchasedetails hqPurchasedetails = new HqPurchasedetails();
            //原材料Id
            hqPurchasedetails.setMaterialId(purchaseAddVo.getMaterialId());
            //材料数量
            hqPurchasedetails.setCount(purchaseAddVo.getCount());
            hqPurchasedetails.setOperator(perUsers.getUserName());
            //材料金额
            hqPurchasedetails.setMoney(purchaseAddVo.getMoney());
            hqPurchasedetails.setPurchaseId(hqPurchaseorder.getPurchaseId());
            hqPurchasedetails.setRemark(remark);
            hqPurchasedetailsService.insert(hqPurchasedetails);
        }
        return insert;
    }

    @Override
    public HqPurchaseorder selectRemarkOperator(String purchaseId) {
        return this.hqPurchaseorderMapper.selectRemarkOperator(purchaseId);
    }

    @Override
    public boolean updatePurchaseorder(String list, String remark, String supName, String purchaseId, HttpSession session) {
        String list3= list.replace("[],","");
        String list4=list3.replace(",[]","");
        List<PurchaseAddVo> list2 = new Tools().jsonToList(list4, PurchaseAddVo.class);
        PerUsers perUsers = (PerUsers)session.getAttribute("perUsers");
        //先删除
        boolean b = hqPurchasedetailsService.deleteMaterials(purchaseId);
        if (list2.get(0)!=null){
            double money = 0;
            for (PurchaseAddVo purchaseAddVo : list2) {
                money+=purchaseAddVo.getCount()*purchaseAddVo.getMoney();
                //采购明细
                HqPurchasedetails hqPurchasedetails = new HqPurchasedetails();
                //原材料Id
                hqPurchasedetails.setMaterialId(purchaseAddVo.getMaterialId());
                //材料数量
                hqPurchasedetails.setCount(purchaseAddVo.getCount());
                hqPurchasedetails.setOperator(perUsers.getUserName());
                //材料金额
                hqPurchasedetails.setMoney(purchaseAddVo.getMoney());
                hqPurchasedetails.setPurchaseId(purchaseId);
                hqPurchasedetails.setRemark(remark);
                hqPurchasedetailsService.insert(hqPurchasedetails);
            }
            hqPurchaseorderMapper.updatePurchaseorder(remark,supName,purchaseId,money);
            hqPurchaseorderMapper.updateisva(purchaseId,AuditStatus.NO_SQ.status);
        }else {
            //修改原材料订单备注、供应商、总金额
            hqPurchaseorderMapper.updatePurchaseorder(remark,supName,purchaseId,0);
            //每次修改的都是状态为未申请
            hqPurchaseorderMapper.updateisva(purchaseId,AuditStatus.NO_SQ.status);
        }
        return b;
    }

    @Override
    public boolean updateisva(String purchaseId,int state) {
        return this.hqPurchaseorderMapper.updateisva(purchaseId,state);
    }

    /**
     * 原材料审核
     * @param purchaseorderVo 原材料订单Vo
     * @param auditRecord   审核
     * @param session   当前会话
     * @return ResponseMessage
     */
    @Override
    public ResponseMessage updateIsva(PurchaseorderVo purchaseorderVo, AuditRecord auditRecord, HttpSession session) {
        PerUsers perUsers = (PerUsers) session.getAttribute("perUsers");
        //修改原材料状态
        this.hqPurchaseorderMapper.updateisva(purchaseorderVo.getPurchaseId(), Integer.valueOf(purchaseorderVo.getIsva()));
        //审核表添加记录
        //添加审核人
        auditRecord.setAuditor(perUsers.getUserName());
        //添加业务id
        auditRecord.setBusinessId(purchaseorderVo.getPurchaseId());
        //判断原材料订单状态是否为总公司财务通过
        if(purchaseorderVo.getIsva().equals(String.valueOf(AuditStatus.RUN_ZGSCWTG.status))){
            //根据采购单id查询采购单
            HqPurchaseorder hqPurchaseorder = hqPurchaseorderMapper.queryById(purchaseorderVo.getPurchaseId());
            //总公司财务出账
            hqFinancingMapper.updateMoney("0", hqPurchaseorder.getPurchaseSumprice(), "2");
            //保存总公司财务明细
            HqRicher hqRicher = new HqRicher();
            //财务id
            hqRicher.setHandFinancingId("0");
            hqRicher.setPurchaseId(purchaseorderVo.getPurchaseId());
            //采购总金额
            hqRicher.setRicherPrice(hqPurchaseorder.getPurchaseSumprice());
            //出账
            hqRicher.setState(2);
            //出账时间
            hqRicher.setRicherTime(new Date());
            hqRicher.setOper(perUsers.getUserName());
            //采购单备注
            hqRicher.setRemark(hqPurchaseorder.getRemark());
            //添加总公司财务明细
            hqRicherMapper.insertSelective(hqRicher);
        }

        return auditRecordMapper.insertSelective(auditRecord) > 0 ? ResponseMessage.success("审核成功") : ResponseMessage.error("审核失败");
    }

    @Override
    public boolean updatePurchaseSumprice(String purchaseId, double purchaseSumprice) {
        return this.hqPurchaseorderMapper.updatePurchaseSumprice(purchaseId,purchaseSumprice);
    }

    @Override
    public List<HqSupplier> showSupName() {
        return this.hqPurchaseorderMapper.showSupName();
    }

    @Override
    public List<Object> showTypeName() {
        return this.hqPurchaseorderMapper.showTypeName();
    }

    @Override
    public List<rawMaterialVo> rawMaterialShowAllByLimit(rawMaterialVo rawMaterialVo) {
        return this.hqPurchaseorderMapper.rawMaterialShowAllByLimit(rawMaterialVo);
    }

    @Override
    public int rawMaterialselectCount(rawMaterialVo rawMaterialVo) {
        return this.hqPurchaseorderMapper.rawMaterialselectCount(rawMaterialVo);
    }

    @Override
    public PurchaseMaterialVo selectPurchaseRemarkSupId(PurchaseMaterialVo purchaseMaterialVo) {
        return this.hqPurchaseorderMapper.selectPurchaseRemarkSupId(purchaseMaterialVo);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param purchaseId 主键
     * @return 实例对象
     */
    @Override
    public HqPurchaseorder queryById(String purchaseId) {
        return this.hqPurchaseorderMapper.queryById(purchaseId);
    }

    @Override
    public int selectCount(PurchaseorderVo purchaseorderVo) {
        return this.hqPurchaseorderMapper.selectCount(purchaseorderVo);
    }

    /**
     * 查询多条数据
     *
     * @param purchaseorderVo
     * @return 对象列表
     */
    @Override
    public List<HqPurchaseorder> queryAllByLimit(PurchaseorderVo purchaseorderVo) {
        return this.hqPurchaseorderMapper.queryAllByLimit(purchaseorderVo);
    }

    /**
     * 新增数据
     *
     * @param hqPurchaseorder 实例对象
     * @return 实例对象
     */
    @Override
    public HqPurchaseorder insert(HqPurchaseorder hqPurchaseorder) {
        this.hqPurchaseorderMapper.insert(hqPurchaseorder);
        return hqPurchaseorder;
    }

    @Override
    public List<PurchaseMaterialVo> selectMaterial(PurchaseMaterialVo purchaseMaterialVo) {
        return this.hqPurchaseorderMapper.selectMaterial(purchaseMaterialVo);
    }

    /**
     * 修改数据
     *
     * @param hqPurchaseorder 实例对象
     * @return 实例对象
     */
    @Override
    public HqPurchaseorder update(HqPurchaseorder hqPurchaseorder) {
        this.hqPurchaseorderMapper.update(hqPurchaseorder);
        return this.queryById(hqPurchaseorder.getPurchaseId());
    }

    /**
     * 通过主键删除数据
     * 删除 订单详细表 、订单表 审核表
     *
     * @param purchaseId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String purchaseId) {
        int i = hqPurchasedetailsService.deleteByPurchaseId(purchaseId);
        hqPurchaseorderMapper.deleteById(purchaseId);
        return i > 0;
    }
}